#!/usr/bin/python2
#-*-python-*-

import getopt
import cf
import sys
import os
import re

# --------------------------------------------------------------------
# Parse command line options
# --------------------------------------------------------------------
iam   = os.path.basename(sys.argv[0])
usage = "USAGE: %s [-a opts] [-f format] [-i] [-o outfile] [-r opts] [-v] FILE [FILE ...]" % iam

try:
    opts, infiles = getopt.getopt(sys.argv[1:], "a:f:io:r:v", 
                                  ['aggregate_options=',
                                   'format=',
                                   'ignore_ioerror',
                                   'outfile=',
                                   'read_options=',                                 
                                   'verbose',
                                   ])
except getopt.GetoptError, err:
    # print help information and exit:
    print iam, str(err)    
    print usage
    sys.exit(2)
#--- End: try

if not infiles:
    print iam,"ERROR: Must provide at least one input netCDF file."
    print usage
    sys.exit(2)
#--- End: if

# Defaults
format_out        = 'NETCDF3_CLASSIC'
directory         = None
outfile           = None
verbose           = False
ignore_ioerror    = False
aggregate_options = {}
read_options      = {'close'         : False,
                     'ignore_ioerror': False,
                     }

for option, arg in opts:
    if option in ('-d', '--directory'):
        directory = arg
        # Try to create non-existent directories
        try:
            os.makedirs(directory)
        except os.error:
            pass
    elif option in ('-f', '--format'):
        format_out = arg
    elif option in ('-o', '--outfile'):
        outfile = arg
    elif option in ('-v', '--verbose'):
        verbose = True
    elif option in ('-a', '--aggregate_options'):
        for opt in arg.split(','):
            key, value = opt.split('=')
            if value == '0':
                value = False
            else:
                value = True
            aggregate_options[key] = value                         
    elif option in ('-r', '--read_options'):
        for opt in arg.split(','):
            key, value = opt.split('=')
            if value == '0':
                value = False
            else:
                value = True
            read_options[key] = value                         
    elif option in ('-i', '--ignore_ioerror'):
        ignore_ioerror = 1
#    elif option in ('-u', '--strict_units'):
#        aggregate_options['strict_units'] = True
    else:
        print usage
        assert False, "Unhandled option: "+option
#--- End: for

if read_options.has_key('aggregate') and not read_options['aggregate']:
    pass
else:
    read_options['aggregate'] = aggregate_options

if outfile is None:
    print iam, 'ERROR: Must set an output file name'
    print usage
    sys.exit(1) 
#--- End: if

# --------------------------------------------------------------------
# Read the input files, aggregate the fields and write them out as one
# netCDF file
# --------------------------------------------------------------------
try:        
    f = cf.read(infiles, **read_options)
except Exception as error:
    print iam, 'ERROR reading file:', error
    sys.exit(1)
#--- End: try

if verbose:
    ninfiles = len(infiles)
    ncf      = len(f)
    print "%d input file%s contain%s %d CF field%s:" % \
        (ninfiles,
         (''  if ninfiles==1 else 's'),
         ('s' if ncf==1      else '' ),
         ncf,
         ('s' if ncf>1 else '' ))
    print repr(f)
#--- End: if

# --------------------------------------------------------------------
# Write the netCDF file
# --------------------------------------------------------------------
if f:
    try:        
        cf.write(f, outfile, format=format_out)
    except Exception as error:
        print iam, 'ERROR writing file:', error
        sys.exit(1)
#--- End: if
